<template>
  <div class="all-music-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">{{ pageTitle }}</h1>
    </div>

    <!-- 曲风描述卡片 -->
    <div v-if="showGenreCard && genreDescription" class="genre-description-card">
      <div class="genre-card-content">
        <p class="genre-description-text">{{ genreDescription }}</p>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading && musicList.length === 0" class="loading-container">
      <div class="loading-spinner">
        <i class="el-icon-loading"></i>
        <span>加载中...</span>
      </div>
    </div>

    <!-- 音乐列表 -->
    <div v-else-if="musicList.length > 0" class="music-list-container">
      <div
        v-for="(music, index) in musicList"
        :key="music.id"
        class="music-item"
        :style="{ animationDelay: `${index * 0.05}s` }"
      >
        <!-- 左侧信息区域 -->
        <div class="music-info-left" @click="toMusicDetail(music.id)">
          <div class="cover-wrapper">
            <img
              :src="
                music.coverUrl || 'https://sky-take-ou7.oss-cn-beijing.aliyuncs.com/default.jpeg'
              "
              :alt="music.title"
              class="cover-image"
            />
          </div>

          <div class="music-details">
            <h3 class="music-title">{{ music.title }}</h3>
            <p class="music-creator">
              <i class="el-icon-user"></i>
              {{ music.creatorNickname || music.creatorName || '未知创作者' }}
            </p>
            <div v-if="music.genres && music.genres.length > 0" class="genre-tags">
              <span v-for="genre in music.genres.slice(0, 3)" :key="genre.id" class="genre-tag">
                {{ genre.name }}
              </span>
            </div>
          </div>
        </div>

        <!-- 右侧播放按钮 -->
        <div class="music-actions">
          <button class="play-btn-large" @click="playMusic(music.id, $event)" title="播放">
            <img src="/src/assets/icon/play_2.svg" alt="播放" width="24" height="24" />
          </button>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="totalMusic"
          :page-sizes="[12, 24, 48, 96]"
          layout="sizes, prev, pager, next, jumper"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 空状态 -->
    <div v-else class="empty-container">
      <div class="empty-state">
        <div class="empty-icon">🎵</div>
        <h3>暂无音乐</h3>
        <p>{{ currentCategory === 'all' ? '还没有音乐被上传' : '该分类下暂无音乐' }}</p>
        <button class="back-btn" @click="goBack">返回首页</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getMusicByGenrePage, getMusicPage } from '../api/music'
import { getUserInfoById } from '../api/user'
import { getGenreById, getGenreByMusicId } from '../api/genre'
import { useUserStore } from '../stores/user'
import { eventBus } from '../utils/eventBus'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 状态
const musicList = ref([])
const currentPage = ref(1)
const pageSize = ref(12)
const totalMusic = ref(0)
const loading = ref(false)
const genreDescription = ref('') // 曲风描述
const showGenreCard = ref(false) // 是否显示曲风卡片

// 计算属性
const currentCategory = computed(() => route.query.category || 'all')
const genreName = computed(() => route.query.genreName || '全部音乐')
const pageTitle = computed(() => {
  return currentCategory.value === 'all' ? '全部音乐' : genreName.value
})

// 获取音乐列表
const fetchMusicList = async () => {
  try {
    loading.value = true
    let res

    if (currentCategory.value !== 'all') {
      // 特定曲风
      res = await getMusicByGenrePage(currentCategory.value, currentPage.value, pageSize.value)
      // 获取曲风描述
      await loadGenreDescription()
    } else {
      // 全部音乐
      res = await getMusicPage(currentPage.value, pageSize.value)
      // 全部音乐时不显示曲风卡片
      showGenreCard.value = false
      genreDescription.value = ''
    }

    const records = res.data?.records || res.data || []
    totalMusic.value = res.data?.total || 0

    // 处理音乐数据
    for (const music of records) {
      // 处理上传者信息
      if (music.creatorIds) {
        try {
          const creatorIdArray = music.creatorIds
            .split('-')
            .map((id) => parseInt(id.trim()))
            .filter((id) => !isNaN(id))

          if (creatorIdArray.length > 0) {
            const creatorPromises = creatorIdArray.map(async (id) => {
              try {
                const userRes = await getUserInfoById(id)
                return userRes.data?.nickname || '未知用户'
              } catch {
                return '未知用户'
              }
            })

            const creatorNicknames = await Promise.all(creatorPromises)
            music.creatorNickname = creatorNicknames[0] || '未知用户'
            music.creatorNicknames = creatorNicknames
          } else {
            music.creatorNickname = '未知用户'
          }
        } catch {
          music.creatorNickname = '未知用户'
        }
      } else {
        music.creatorNickname = '未知用户'
      }

      // 获取三级曲风信息
      try {
        const genreRes = await getGenreByMusicId(music.id)
        if (genreRes && genreRes.data) {
          if (Array.isArray(genreRes.data)) {
            music.genres = genreRes.data
          } else if (Array.isArray(genreRes.data.data)) {
            music.genres = genreRes.data.data
          } else {
            music.genres = []
          }
        } else {
          music.genres = []
        }
      } catch (error) {
        // 静默处理404错误，可能是音乐没有关联曲风
        music.genres = []
      }
    }

    musicList.value = records
  } catch (error) {
    console.warn('获取音乐列表失败:', error.message || error)
    musicList.value = []
    totalMusic.value = 0
  } finally {
    loading.value = false
  }
}

// 播放音乐
const playMusic = (musicId, event) => {
  event.stopPropagation()
  console.log('播放音乐:', musicId)
  // 查找完整的音乐对象
  const music = musicList.value.find((item) => item.id === musicId)
  if (music) {
    // 发送播放事件，传递完整的音乐对象
    eventBus.emit('playMusic', music)
  } else {
    console.error('未找到音乐:', musicId)
    ElMessage.error('未找到该音乐')
  }
}

// 跳转到音乐详情
const toMusicDetail = (musicId) => {
  router.push(`/music/${musicId}`)
}

// 返回
const goBack = () => {
  router.push('/')
}

// 加载曲风描述
const loadGenreDescription = async () => {
  if (currentCategory.value === 'all') {
    showGenreCard.value = false
    genreDescription.value = ''
    return
  }

  try {
    const response = await getGenreById(currentCategory.value)
    if (response.code === 200 && response.data) {
      genreDescription.value = response.data.description || '暂无描述'
      showGenreCard.value = true
    } else {
      genreDescription.value = '探索这个曲风的精彩音乐世界'
      showGenreCard.value = true
    }
  } catch (error) {
    // 静默处理404错误，可能是曲风不存在
    if (error.response?.status !== 404) {
      console.warn('获取曲风描述失败:', error.message)
    }
    genreDescription.value = '探索这个曲风的精彩音乐世界'
    showGenreCard.value = true
  }
}

// 分页处理
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchMusicList()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchMusicList()
}

// 监听路由变化
watch(
  () => route.query,
  () => {
    currentPage.value = 1
    fetchMusicList()
  },
)

// 初始化
onMounted(() => {
  fetchMusicList()
})
</script>

<style scoped>
.all-music-page {
  min-height: 100vh;
  background: transparent;
  padding: 2rem 1rem;
}

.page-header {
  text-align: center;
  margin-bottom: 3rem;
}

.page-header h1 {
  font-size: 2.5rem;
  font-weight: 700;
  color: #2c3e50;
  margin-bottom: 0.5rem;
}

.page-subtitle {
  font-size: 1.1rem;
  color: #7f8c8d;
  margin-bottom: 0.5rem;
}

.genre-description {
  font-size: 1rem;
  color: #95a5a6;
  max-width: 600px;
  margin: 0 auto;
  line-height: 1.5;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 50vh;
}

.loading-spinner {
  text-align: center;
  color: var(--primary-color);
}

.loading-spinner i {
  font-size: 3rem;
  margin-bottom: 1rem;
}

.music-list-container {
  max-width: 1200px;
  margin: 0 auto;
}

.music-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: white;
  margin-bottom: 1rem;
  padding: 1rem;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  animation: fadeInUp 0.4s ease-out;
  animation-fill-mode: both;
}

.music-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.music-info-left {
  display: flex;
  align-items: center;
  flex: 1;
  cursor: pointer;
}

.cover-wrapper {
  position: relative;
  width: 80px;
  height: 80px;
  border-radius: 8px;
  overflow: hidden;
  margin-right: 1rem;
}

.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.music-details {
  flex: 1;
}

.music-title {
  font-size: 1.2rem;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 0.5rem;
}

.music-creator {
  font-size: 0.9rem;
  color: #7f8c8d;
  margin-bottom: 0.5rem;
  display: flex;
  align-items: center;
  gap: 0.25rem;
}

.genre-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 0.25rem;
}

.genre-tag {
  font-size: 0.75rem;
  padding: 0.25rem 0.5rem;
  background: rgba(29, 185, 84, 0.1);
  color: var(--primary-color);
  border-radius: 12px;
  border: 1px solid rgba(29, 185, 84, 0.2);
}

.music-actions {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.play-btn-large {
  width: 50px;
  height: 50px;
  border: none;
  background: #27ae60;
  color: white;
  border-radius: 50%;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.play-btn-large:hover {
  background: #2ecc71;
  transform: scale(1.1);
  box-shadow: 0 4px 12px rgba(39, 174, 96, 0.3);
}

.pagination-container {
  margin-top: 3rem;
  display: flex;
  justify-content: center;
  padding: 0 1rem;
}

/* 绿色分页按钮样式 */
:deep(.el-pagination) {
  --el-pagination-button-bg-color: #27ae60;
  --el-pagination-button-text-color: white;
  --el-pagination-button-disabled-bg-color: #95a5a6;
  --el-pagination-button-hover-bg-color: #2ecc71;
  --el-pagination-bg-color: #27ae60;
  --el-pagination-text-color: white;
}

:deep(.el-pagination.is-background .btn-prev),
:deep(.el-pagination.is-background .btn-next),
:deep(.el-pagination.is-background .el-pager li) {
  background-color: #27ae60;
  color: white;
  border: none;
}

:deep(.el-pagination.is-background .el-pager li:hover) {
  background-color: #2ecc71;
}

:deep(.el-pagination.is-background .el-pager li.active) {
  background-color: #1e8449;
}

:deep(.el-pagination.is-background .btn-prev:hover),
:deep(.el-pagination.is-background .btn-next:hover) {
  background-color: #2ecc71;
}

:deep(.el-pagination.is-background .btn-prev:disabled),
:deep(.el-pagination.is-background .btn-next:disabled) {
  background-color: #95a5a6;
  color: #bdc3c7;
}

.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60vh;
}

.empty-state {
  text-align: center;
  color: #7f8c8d;
}

.empty-icon {
  font-size: 4rem;
  margin-bottom: 1rem;
  opacity: 0.6;
}

.empty-state h3 {
  font-size: 1.5rem;
  color: #2c3e50;
  margin-bottom: 0.5rem;
}

.back-btn {
  margin-top: 1rem;
  padding: 0.75rem 2rem;
  background: var(--primary-color);
  color: white;
  border: none;
  border-radius: 25px;
  cursor: pointer;
  font-size: 1rem;
  transition: all 0.3s ease;
}

.back-btn:hover {
  background: var(--primary-hover);
  transform: translateY(-2px);
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@media (max-width: 768px) {
  .all-music-page {
    padding: 1rem;
  }

  .page-header h1 {
    font-size: 2rem;
  }

  .music-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 1rem;
  }

  .music-info-left {
    width: 100%;
  }

  .music-actions {
    align-self: center;
  }

  .cover-wrapper {
    width: 60px;
    height: 60px;
  }
}

/* 曲风描述卡片 */
.genre-description-card {
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  border: 1px solid #e9ecef;
  border-left: 4px solid #27ae60;
  border-radius: 8px;
  padding: 1.2rem 1.5rem;
  margin: 1rem auto 2rem auto;
  max-width: 800px;
  width: 90%;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.genre-description-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 2px;
  background: linear-gradient(90deg, #27ae60, #2ecc71, #27ae60);
  opacity: 0.7;
}

.genre-description-card:hover {
  box-shadow: 0 2px 8px rgba(39, 174, 96, 0.15);
  transform: translateY(-1px);
  border-left-color: #2ecc71;
}

.genre-description-text {
  font-size: 0.95rem;
  line-height: 1.7;
  color: #495057;
  margin: 0;
  text-align: justify;
  word-wrap: break-word;
  overflow-wrap: break-word;
  font-weight: 400;
  letter-spacing: 0.3px;
}

.genre-description-text::before {
  content: '♪ ';
  color: #27ae60;
  font-size: 1.1rem;
  margin-right: 0.3rem;
}

.genre-description-text::after {
  content: ' ♪';
  color: #27ae60;
  font-size: 1.1rem;
  margin-left: 0.3rem;
}

@media (max-width: 768px) {
  .genre-description-card {
    padding: 1rem 1.2rem;
    margin: 0.8rem auto 1.5rem auto;
    width: 92%;
    border-left-width: 3px;
  }

  .genre-description-text {
    font-size: 0.9rem;
    line-height: 1.6;
    letter-spacing: 0.2px;
  }

  .genre-description-text::before,
  .genre-description-text::after {
    font-size: 1rem;
  }
}
</style>
